package com.ghsc.ghxc.jsb.ui.mall

import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.arialyy.annotations.DownloadGroup
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.common.HttpOption
import com.arialyy.aria.core.processor.IHttpFileLenAdapter
import com.arialyy.aria.core.task.DownloadGroupTask
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.KeyboardUtils.hideKeyboard
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentMallBinding
import com.ghsc.ghxc.jsb.ext.copyToClipboard
import com.ghsc.ghxc.jsb.ext.invisible
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialChildInfoBean
import com.ghsc.ghxc.jsb.ui.mall.bean.MaterialBean
import com.ghsc.ghxc.jsb.ui.mall.view.SourceSharePopupView
import com.ghsc.ghxc.jsb.view.NotDataView
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.permissionx.guolindev.PermissionX
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.zzhoujay.richtext.RichText
import java.io.File
import java.util.ArrayList

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.mall
 * 类名：MallFragment
 * 创建时间：2024/4/23 15:00
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class MallFragment  : BaseVMFragment<MallViewModel, FragmentMallBinding>(R.layout.fragment_mall){
    override fun attachVMClass(): Class<MallViewModel>? {
        return MallViewModel::class.java
    }

    override fun lazyLoad() {
    }



    private val mAdapter: ListAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<MaterialBean>()
    private var notDataView: View? = null


    var keyword = ""


    override fun initView(savedInstanceState: Bundle?) {
        Aria.download(this).register()
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        mAdapter.addChildClickViewIds(R.id.stvCopy,R.id.btnShare)
        notDataView = NotDataView.notDataView(requireActivity(), binding.rvList,binding.refreshLayout,"暂无数据")
        initRefreshLayout()
        pageNo = 1
        getListData()

    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["psize"] = "20"
        map["pindex"] = pageNo
        map["stype"] = 3
        map["keyword"] = keyword
        loge("素材列表请求参数="+map.toString())
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.suCaiListMethod(it1) }

    }
    override fun initData() {
        super.initData()
    }
    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnClose.setSingleClickListener {
            keyword=""
            binding.etSearch.setText("")
            hideKeyboard(binding.etSearch)
        }
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }else {
                keyword=""
                pageNo = 1
                getListData()
            }
        }
        binding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(
                v: TextView,
                actionId: Int,
                event: KeyEvent?
            ): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    hideKeyboard(v)
                    // 搜索，进行自己要的操作...
                    if (binding.etSearch.text.toString().trim().isNotEmpty()){
                        keyword = binding.etSearch.text.toString().trim()
                        pageNo = 1
                        getListData()
                    }else{
                        keyword =""
                        pageNo = 1
                        getListData()
                    }
                    return true
                }
                return false
            }
        })
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                if(TextUtils.isEmpty(p0.toString().trim())){
                    keyword =""
                    pageNo = 1
                    getListData()
                }
            }

        })

        mAdapter.setOnFastChildClickListener { view, position ->
            if (view.id == R.id.stvCopy){
                val data = mAdapter.data[position]
                PermissionX.init(this)
                    .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request { allGranted, _, _ ->
                        loge("获取到权限了吗="+allGranted)
                        if (allGranted) {
                            setDownloadData(data)
                        } else {
                            showToast("请开启存储权限")
                        }
                    }
            }else if(view.id==R.id.btnShare){
                //一键转发
                XPopup.Builder(requireActivity())
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                    .customHostLifecycle(lifecycle)
                    .dismissOnTouchOutside(true)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        SourceSharePopupView(requireActivity(),mAdapter.data[position] )
                    )
                    .show()
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MallFragment) {
                showToast(it)
            }
            againLoginMsg.observe(this@MallFragment) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            suCaiListData.observe(this@MallFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    }
                    else {
                        mAdapter.replaceData(it.data.list)
                        if (it.data.list.size < 20) {
                            binding.refreshLayout.finishRefreshWithNoMoreData()
                        }
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty()){
                        mAdapter.addData(it.data.list)
                    }
                    if (it.data.list.size < 20) {
                        binding.refreshLayout.finishRefreshWithNoMoreData()
                    }
                }
            }


        }
    }
    private fun setDownloadData(data: MaterialBean) {
        val downloadUrls = mutableListOf<String>()
        if (data.images.isNotEmpty()){
            data.images.forEach {
                if (!TextUtils.isEmpty(it.url)){
                    downloadUrls.add(it.url)
                }
            }
        }
        if (data.videos.isNotEmpty()){
            data.videos.forEach {
                if (!TextUtils.isEmpty(it.url)){
                    downloadUrls.add(it.url)
                }
            }
        }
        download(downloadUrls)
    }

    private val downloadPath = Environment.getExternalStorageDirectory().path + "/Download/material"
    private fun download(urls:MutableList<String>){
        if (urls.isNotEmpty()){
            showLoading()
            Aria.download(this)
                .loadGroup(urls)
                .setDirPath(downloadPath)
                .setSubFileName(setSubFileName(urls))
                .unknownSize()
                .option(getHttpOption())
                .ignoreFilePathOccupy()
                .create()
        }
    }

    private fun setSubFileName(urls:MutableList<String>): MutableList<String> {
        val fileNames = mutableListOf<String>()
        urls.forEachIndexed { index, it ->
            if (it.contains(".")){
                val split = it.split(".")
                fileNames.add("guohua_${System.currentTimeMillis()}_${index}.${split[split.size - 1]}")
            }
        }
        return fileNames
    }

    private fun getHttpOption(): HttpOption {
        val option = HttpOption()
        option.setFileLenAdapter(HttpFileLenAdapter())
        return option
    }

    internal class HttpFileLenAdapter : IHttpFileLenAdapter {
        override fun handleFileLen(headers: Map<String, List<String>>): Long {
            val sLength = headers["Content-Length"]
            if (sLength == null || sLength.isEmpty()) {
                return -1
            }
            val temp = sLength[0]
            return temp.toLong()
        }
    }
    @DownloadGroup.onTaskComplete
    fun taskComplete(task: DownloadGroupTask) {
        loge("下载素材=====taskComplete")
        dismissLoading()
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri: Uri = Uri.fromFile(File(downloadPath))
        intent.data = uri
        requireActivity().sendBroadcast(intent)
//        copyToClipboard(requireActivity(),,"素材下载完成，文案已复制")
        showToast("素材下载完成")
    }

    @DownloadGroup.onTaskFail
    fun taskFail(task: DownloadGroupTask?) {
        loge("下载素材=====taskFail")
        dismissLoading()
    }

    @DownloadGroup.onTaskStart
    fun taskStart(task: DownloadGroupTask) {
        loge("下载素材=====task")
    }

    @DownloadGroup.onTaskRunning
    protected fun running(task: DownloadGroupTask) {
        loge("下载素材=====running")
    }





    ////
    inner class ListAdapter   : BaseQuickAdapter<MaterialBean, BaseViewHolder>(
        R.layout.layout_material_list_item) {
        override fun convert(helper: BaseViewHolder, item: MaterialBean) {
            GlideUtil.ImageHeadLoad(context, item.headimg, helper.getView(R.id.ivHeader))
            helper.setText(R.id.tvName,item.nickname)
                .setText(R.id.tvDate,item.publish_time)
            if(!TextUtils.isEmpty(item.content)){
                helper.setGone(R.id.tvDetail,false)
//                val webSettings: WebSettings = webView.settings
//                webSettings.javaScriptEnabled = true //允许使用js
//                //设置WebView是否支持使用屏幕控件或手势进行缩放，默认是true，支持缩放
//                webSettings.setSupportZoom(false)
//                //设置WebView是否使用其内置的变焦机制，该机制集合屏幕缩放控件使用，默认是false，不使用内置变焦机制
//                webSettings.builtInZoomControls = false
//                //置WebView使用内置缩放机制时，是否展现在屏幕缩放控件上，默认true，展现在控件上
//                webSettings.displayZoomControls = false
////                webView.addJavascriptInterface(AndroidInterface(),"android")
//                webView.loadData(item.content, "text/html", "UTF-8")
//                RichText.fromHtml( item.content ).into(helper.getView(R.id.tvDetail))
                 helper.setText(R.id.tvDetail,item.content)
            }else{
                helper.setGone(R.id.tvDetail,true)
            }
            val images = item.images
            val videos = item.videos
            val materialChildList = mutableListOf<MaterialChildInfoBean>()
            var selectList: MutableList<LocalMedia> = ArrayList()
            if (images.isNotEmpty()){
                images.forEach {
                    materialChildList.add(MaterialChildInfoBean(0,it.url))
                    val localMedia = LocalMedia()
                    localMedia.path = it.url
                    localMedia.mimeType= PictureMimeType.MIME_TYPE_IMAGE
                    selectList.add(localMedia)
                }
            }
            if (videos.isNotEmpty()){
                videos.forEach {
                    materialChildList.add(MaterialChildInfoBean(1,it.url))
                    val localMedia = LocalMedia()
                    localMedia.path = it.url
                    localMedia.mimeType= PictureMimeType.MIME_TYPE_VIDEO
                    selectList.add(localMedia)
                }
            }
            if(materialChildList.size>0){
                helper.setGone(R.id.rvImg,false)
                val rvImg = helper.getView<RecyclerView>(R.id.rvImg)
                val llImage = helper.getView<LinearLayout>(R.id.llImage)
                if(materialChildList.size==1){
                    val image1 = helper.getView<ImageView>(R.id.image1)
                    val image2 = helper.getView<ImageView>(R.id.image2)
                    llImage.visible()
                    image1.visible()
                    image2.invisible()
                    GlideUtil.ImageHeadLoad(context, materialChildList[0].url,image1)
                    image1.setSingleClickListener {
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(activity)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(0, selectList)
                    }
                }else if(materialChildList.size==2){
                    val image1 = helper.getView<ImageView>(R.id.image1)
                    val image2 = helper.getView<ImageView>(R.id.image2)
                    llImage.visible()
                    image1.visible()
                    image2.visible()
                    GlideUtil.ImageHeadLoad(context, materialChildList[0].url,image1)
                    GlideUtil.ImageHeadLoad(context, materialChildList[1].url,image2)
                    image1.setSingleClickListener {
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(activity)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(0, selectList)
                    }
                    image2.setSingleClickListener {
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(activity)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(1, selectList)
                    }
                }else{
                    rvImg.layoutManager = GridLayoutManager(requireActivity(),3)
                    val materialChildListAdapter = MaterialChildListAdapter()
                    rvImg.adapter = materialChildListAdapter
                    materialChildListAdapter.replaceData(materialChildList)
                    materialChildListAdapter.setOnItemClickListener { adapter, view, position ->
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(activity)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(position, selectList)
                    }
                }
            }else{
                helper.setGone(R.id.rvImg,true)
            }

        }
    }
    inner class MaterialChildListAdapter   : BaseQuickAdapter<MaterialChildInfoBean, BaseViewHolder>(
        R.layout.layout_material_list_img_item) {
        override fun convert(helper: BaseViewHolder, item: MaterialChildInfoBean) {
            GlideUtil.ImageLoad(context, item.url, helper.getView(R.id.imageView))
            helper.setGone(R.id.ivPlayer, item.type == 0)
            helper.setGone(R.id.isVideo, item.type == 0)

        }
    }


}